了解Servlet的生命週期是很重要的,因為知道他的流程我們才能在不同階段做我們想要做的事。
@WebServlet("/")
public class DemoLifeCycleServlet implements Servlet {
@Override
public void init(ServletConfig config) throws ServletException {
System.out.println("servlet init");
}
@Override
public ServletConfig getServletConfig() {
return null;
}
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
System.out.println("service");
}
@Override
public String getServletInfo() {
return "";
}
@Override
public void destroy() {
System.out.println("servlet destroy");
}
}
Servlet Life Cycle,也就是從Servlet實例化開始到銷毀的過程,可分成以下階段
根據上面的範例我們啟動server後可以訪問locahost:8080/多次後再關閉server,會看到以下log
[2024-08-19 10:59:18,064] Artifact day06:war exploded: Artifact is deployed successfully
[2024-08-19 10:59:18,065] Artifact day06:war exploded: Deploy took 291 milliseconds
DemoLifeCycleServlet constructor
servlet init
service
service
service
servlet destroy
default是-1,tomcat啟動時不實例化servlet
正整數,tomcat啟動時實例化servlet,按照數字小到到大,序號衝突tomcat會自動調整
@WebServlet(value = "/",loadOnStartup = 10)
public class DemoLifeCycleServlet implements Servlet {
//略
}
可以看到與上面log不同的是這裡啟動tomcat就把servlet帶起來了
DemoLifeCycleServlet constructor
servlet init
[2024-08-19 11:29:52,441] Artifact day06:war exploded: Artifact is deployed successfully
[2024-08-19 11:29:52,441] Artifact day06:war exploded: Deploy took 287 milliseconds
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd"
version="6.0">
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>DemoLifeCycle</servlet-name>
<servlet-class>com.swj.DemoLifeCycleServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DemoLifeCycle</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
從tomcat目錄下conf/web.xml可以找到default servlet的設定,靜態資源會透過default servlet來完成response,要注意的是未來使用SpringMVC時因為他有DispatchServlet,若未再特別設置讓DefaultServlet生效,將會造成靜態資源無法得到response的問題。
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>default</servlet-name>
<servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>listings</param-name>
<param-value>false</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
reference:A Servlet's Life cycle - NTU SG